import { defHttp } from '/@/utils/http/axios';
import { entityTableParams } from '/@/api/thingsborad/entity/model/entityModel';
import { deleteEntity, getEntityDeviceList } from '/@/api/thingsborad/entity/entity';
import { getAllDevices } from '/@/views/DigitalTwin/newleft/service/defaultId';

// 安全增强版批量删除方法
export const deleteAllDevices = async (searchParams?: Parameters<typeof getAllDevices>[0]) => {
  // 二次确认
  if (!window.confirm('即将删除所有匹配设备，该操作不可逆！确定继续吗？')) return;

  try {
    // 获取符合条件的所有设备
    const devices = await getAllDevices(searchParams);

    // 进度跟踪
    let successCount = 0;
    let errorCount = 0;

    // 并行删除（建议限制并发数）
    await Promise.all(
      devices.map(async (device) => {
        try {
          await deleteEntity({
            entityType: 'device',
            entityId: device.id.id, // 根据实际数据结构调整
          });
          successCount++;
        } catch (e) {
          console.error(`删除设备 ${device.id.id} 失败:`, e);
          errorCount++;
        }
      }),
    );

    // 结果反馈
    const msg = [
      `操作完成:`,
      `成功删除 ${successCount} 台设备`,
      `${errorCount} 台设备删除失败`,
    ].join('\n');

    alert(msg);
  } catch (error) {
    console.error('批量删除流程错误:', error);
    alert('获取设备列表失败，请检查控制台');
  }
};

// 快捷键绑定（建议仅在开发环境启用）
export const initDeleteShortcut = () => {
  const handleKeyPress = (e: KeyboardEvent) => {
    if (e.key === 'd' && !e.ctrlKey && !e.metaKey && !e.altKey) {
      deleteAllDevices().catch(console.error);
    }
  };

  window.addEventListener('keypress', handleKeyPress);
  return () => window.removeEventListener('keypress', handleKeyPress);
};
